﻿Public Class Gestion_Tipos_Documentos
    Enum estado
        inicial
        insertar
        modificar
        terminado
    End Enum
    Dim operacion As estado = estado.inicial
    Dim id As String = ""
    Dim tratamiento As New Tratamiento_Objetos
    Dim datos As New datos

    Private Sub botones(ByVal flag As Boolean)
        Me.btn_nuevo.Enabled = flag
        Me.btn_salir.Enabled = flag
        Me.btn_cancelar.Enabled = Not flag
        Me.btn_guardar.Enabled = Not flag
        Me.btn_eliminar.Enabled = Not flag
        Me.btn_modificar.Enabled = Not flag
    End Sub
    Private Sub habilitar(ByVal value As Boolean)
        For Each objeto As System.Windows.Forms.Control In Me.Controls
            If TypeOf objeto Is System.Windows.Forms.TextBox Then
                objeto.Enabled = value
            End If
            If TypeOf objeto Is ComboBox Then
                objeto.Enabled = value
            End If
            If TypeOf objeto Is MaskedTextBox Then
                objeto.Enabled = value
            End If
        Next
    End Sub

    Private Sub limpiar()
        For Each objeto As System.Windows.Forms.Control In Me.Controls
            If TypeOf objeto Is System.Windows.Forms.TextBox Then
                objeto.Text = ""
            End If
            If TypeOf objeto Is ComboBox Then
                Dim actual As ComboBox = objeto
                actual.SelectedIndex = -1
            End If
            If TypeOf objeto Is MaskedTextBox Then
                objeto.Text = ""
            End If
        Next
    End Sub

    Private Function validar() As Boolean
        Dim flag As Boolean = True
        If String.IsNullOrEmpty(Me.txt_nombre.Text) Then
            lbl_nombre.ForeColor = Color.Red
            txt_nombre.Focus()
            flag = False
        Else
            lbl_nombre.ForeColor = Color.Black
        End If

        Return flag
    End Function

    Private Sub labels_Color(ByVal color As Color)
        For Each objeto As System.Windows.Forms.Control In Me.Controls
            If TypeOf objeto Is System.Windows.Forms.Label Then
                objeto.ForeColor = color
            End If
        Next
    End Sub

    Private Function validarUso() As Boolean
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim tabla As New Data.DataTable
        Dim consulta As String = "select * from cliente where id_tipo_documento = '" & id & "'"
        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = consulta
        tabla.Load(cmd.ExecuteReader())
        conexion.Close()
        If tabla.Rows.Count = 0 Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Sub Gestion_Tipos_Documentos_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        botones(True)
        cargarTipoDocumentos()
        habilitar(False)
        btn_nuevo.Focus()
    End Sub


    Private Sub DataGridView1_CellDoubleClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs)
        Me.operacion = estado.modificar
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim tabla As New Data.DataTable
        id = DataGridView1.CurrentRow.Cells("id_tipo_documento").Value
        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "select * from tipo_documento where id_tipo_documento = " & id
        tabla.Load(cmd.ExecuteReader())
        If tabla.Rows.Count >= 1 Then
            txt_nombre.Text = tabla.Rows(0)("nombre")
        End If
        conexion.Close()

        Me.habilitar(True)
        botones(False)
        Me.btn_guardar.Enabled = False
        tratamiento.labels_Color(Color.Black, Me.Controls)
    End Sub

    Private Sub Gestion_Tipo_Documento_FormClosing(ByVal sender As System.Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles MyBase.FormClosing
        If operacion = estado.terminado Or operacion = estado.inicial Then
            If MessageBox.Show("¿Desea salir?", "Alerta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.No Then
                e.Cancel = True
            End If
        Else
            MessageBox.Show("Termine la operacion actual!", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)
            e.Cancel = True
        End If

    End Sub

    Private Sub cargarTipoDocumentos()
         Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand
        Dim data As New Data.DataTable


        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "select * from tipo_documento"
        data.Load(cmd.ExecuteReader())
        conexion.Close()
        Dim fila As Integer = 0

        DataGridView1.Rows.Clear()

        For fila = 0 To data.Rows.Count - 1
            DataGridView1.Rows.Add()
            DataGridView1.Rows(fila).Cells(0).Value = data.Rows(fila)("id_tipo_documento")
            DataGridView1.Rows(fila).Cells(1).Value = data.Rows(fila)("nombre")
        Next
    End Sub

    Private Function guardar() As Integer
        Dim conexion As New SqlClient.SqlConnection
        Dim cmd As New SqlClient.SqlCommand

        conexion.ConnectionString = datos._cadena
        conexion.Open()
        cmd.Connection = conexion
        cmd.CommandType = CommandType.Text
        cmd.CommandText = "insert into tipo_documento(nombre) values ('" & txt_nombre.Text & "')"
        Dim temporal As Integer = cmd.ExecuteNonQuery
        conexion.Close()
        Return temporal
    End Function

    Private Sub btn_nuevo_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_nuevo.Click
        operacion = estado.insertar
        botones(False)
        Me.btn_eliminar.Enabled = False
        Me.btn_modificar.Enabled = False
        Me.habilitar(True)
        Me.txt_nombre.Focus()
    End Sub

    Private Sub btn_guardar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_guardar.Click
        If validar() = True Then
            If MessageBox.Show("¿Desea guardar el tipo de documento?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                If guardar() = 1 Then
                    MessageBox.Show("Carga realizada con exito.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    cargarTipoDocumentos()
                    operacion = estado.terminado
                Else
                    MessageBox.Show("Error al realizar la carga.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                End If
                limpiar()
                habilitar(False)
                botones(True)
                btn_nuevo.Focus()
            End If
        End If
    End Sub

    Private Sub btn_modificar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_modificar.Click
        If validar() = True Then
            If MessageBox.Show("¿Desea modificar el tipo de documento?", "Consulta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                Dim conexion As New SqlClient.SqlConnection
                Dim cmd As New SqlClient.SqlCommand
                Dim consulta As String = ""
                conexion.ConnectionString = datos._cadena
                conexion.Open()
                consulta = "update tipo_documento"
                consulta &= " set nombre = '" & Me.txt_nombre.Text & "'"
                consulta &= " where id_tipo_documento = " & id
                cmd.CommandType = CommandType.Text
                cmd.CommandText = consulta
                cmd.Connection = conexion
                Dim filas As Integer = cmd.ExecuteNonQuery()
                conexion.Close()

                If filas = 1 Then
                    MessageBox.Show("Modificacion realizada.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    operacion = estado.inicial
                Else
                    MessageBox.Show("Error al modificar", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    operacion = estado.inicial
                End If

                cargarTipoDocumentos()
                limpiar()
                habilitar(False)
                operacion = estado.terminado
                botones(True)
            End If
        End If
    End Sub

    Private Sub btn_cancelar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_cancelar.Click
        If operacion = estado.insertar Then
            If MessageBox.Show("¿Desea cancelar la carga?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                limpiar()
                labels_Color(Color.Black)
                habilitar(False)
                Me.btn_nuevo.Focus()
                botones(True)
                operacion = estado.inicial
            End If
        Else
            If MessageBox.Show("¿Desea cancelar la modificacion?", "Confirmacion", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
                limpiar()
                labels_Color(Color.Black)
                habilitar(False)
                Me.btn_nuevo.Focus()

                botones(True)
                operacion = estado.inicial
            End If
        End If
    End Sub

    Private Sub btn_eliminar_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_eliminar.Click
        If MessageBox.Show("¿Desea eliminar el tipo de documento?", "Pregunta", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = Windows.Forms.DialogResult.Yes Then
            If validarUso() = False Then
                Dim conexion As New SqlClient.SqlConnection
                Dim cmd As New SqlClient.SqlCommand
                Dim consulta As String = "delete from tipo_documento where id_tipo_documento = '" & id & "'"

                conexion.ConnectionString = datos._cadena
                conexion.Open()
                cmd.Connection = conexion
                cmd.CommandType = CommandType.Text
                cmd.CommandText = consulta
                Dim filas As Integer = cmd.ExecuteNonQuery()
                conexion.Close()
                If filas = 1 Then
                    MessageBox.Show("Eliminacion realizada.", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
                    cargarTipoDocumentos()
                    operacion = estado.inicial
                Else
                    MessageBox.Show("Error al eliminar", "Notificacion", MessageBoxButtons.OK, MessageBoxIcon.Error)
                    operacion = estado.inicial
                End If
                limpiar()
                habilitar(False)
                botones(True)
            Else
                MessageBox.Show("Existen clientes usando este tipo de documento. Elimine los clientes.", "Informacion", MessageBoxButtons.OK, MessageBoxIcon.Information)
            End If
        End If
    End Sub

    Private Sub btn_salir_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_salir.Click
        Close()
    End Sub
End Class